<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import {
  getAssignList2Api,
  deleteAssignApi,
  queryTaskApi,
  addAssignApi
} from '@/api/dispatch/taskpool'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive, watch, computed } from 'vue'
import Write from './components/Write.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { TaskAssignmentType, TaskType } from '@/api/dispatch/taskpool/types'
import { ElButton, ElInput, ElLink, ElMessage, ElPopover, ElSelect, ElTag } from 'element-plus'
import { Icon } from '@iconify/vue'
import UserTable from '@/views/Dispatch/TaskPool/AssignUser/components/UserTable.vue'
import { useUserStoreWithOut } from '@/store/modules/user'
import Assign from '@/views/Dispatch/TaskPool/AssignUser/Assign.vue'
import { useEventBus } from '@/hooks/event/useEventBus'

const ids = ref<string[] | number[]>([])

const userStore = useUserStoreWithOut()
const userStr = computed(() => userStore.getUserStr)

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getAssignList2Api({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data,
      total: res.count
    }
  },

  fetchDelApi: async () => {
    const res = await deleteAssignApi(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { task, ...param } = params
  searchParams.value = { ...param, task: JSON.stringify(task) }
  getList()
}

const { t } = useI18n()

const queryLoading = ref(false)
const ticketOptions = ref([])
const ticketRemoteMethod = async (query: string) => {
  if (query) {
    queryLoading.value = true
    try {
      const res = await queryTaskApi({ ticket_id: query })
      if (res) {
        ticketOptions.value = res.data
      }
    } finally {
      queryLoading.value = false
    }
  } else {
    ticketOptions.value = []
  }
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    fixed: true,
    type: 'selection',
    width: 80,
    selectable: (data) => data.team_leader === userStr.value,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'index',
    label: t('common.index'),
    type: 'index',
    width: 80,
    fixed: true,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'ticket_id',
    label: '工单号',
    fixed: true,
    form: {
      hidden: true
    },
    search: {
      component: 'Select',
      componentProps: {
        filterable: true,
        remote: true,
        remoteMethod: ticketRemoteMethod,
        remoteShowSuffix: true,
        loading: queryLoading,
        options: ticketOptions
      }
    }
    // form: {
    //   component: 'Select',
    //   componentProps: {
    //     filterable: true,
    //     remote: true,
    //     remoteMethod: ticketRemoteMethod,
    //     remoteShowSuffix: true,
    //     loading: queryLoading,
    //     options: ticketOptions,
    //     onChange: (v) => {
    //       const list = ticketOptions.value.filter((item: any) => item.value == v)
    //       selected.value.ticket = list[0]
    //     }
    //   }
    // }
  },
  {
    field: 'ao_id',
    label: 'AO号',
    fixed: true,
    form: {
      hidden: true
    }
  },
  {
    field: 'product_type',
    label: '型号',
    fixed: true,
    form: {
      hidden: true
    }
  },
  {
    field: 'flight',
    label: '架次',
    fixed: true,
    search: {
      componentProps: {
        placeholder: '多架次用英文逗号分隔'
      }
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'station',
    label: '工位',
    fixed: true,
    form: {
      hidden: true
    }
  },
  {
    field: 'position',
    label: '站位',
    fixed: true,
    form: {
      hidden: true
    }
  },
  {
    field: 'team',
    label: '班组',
    fixed: true,
    form: {
      hidden: true
    }
  },
  {
    field: 'team_leader',
    label: '班组长',
    fixed: true,
    form: {
      hidden: true
    }
  },
  {
    field: 'plan_start',
    label: '计划开始日期',
    table: {
      hidden: true
    },
    form: {
      hidden: true
    },
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  },
  // {
  //   field: 'userid',
  //   label: '派工对象工号',
  //   fixed: true,
  //   form: {
  //     hidden: true
  //   }
  // },
  // {
  //   field: 'username',
  //   label: '派工对象姓名',
  //   fixed: true,
  //   form: {
  //     hidden: true
  //   }
  // },
  {
    field: 'assign_users',
    label: '派工',
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElPopover
                trigger="click"
                width="800px"
                v-slots={{
                  reference: () => {
                    return (
                      <ElLink>
                        {data.row?.assign_users && data.row.assign_users.length > 0 ? (
                          <ElTag type="primary"> {data.row.assign_users.length} 人</ElTag>
                        ) : (
                          <ElTag type="warning">无</ElTag>
                        )}
                      </ElLink>
                    )
                  },
                  default: () => {
                    return (
                      <Assign
                        data={data.row}
                        ticketId={data.row.ticket_id}
                        showAction={data.row.team_leader === userStr.value}
                      />
                    )
                  }
                }}
              />
            </>
          )
        }
      }
    },
    search: {
      hidden: true
    },
    form: {
      formItemProps: {
        slots: {
          default: () => {
            return (
              <ElButton onClick={() => (selectUserDialog.value = true)}>
                <Icon icon="ep:circle-plus" />
              </ElButton>
            )
          }
        }
      }
    }
  }
  // {
  //   field: 'create_datetime',
  //   label: '创建时间',
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     hidden: true
  //   }
  // }
])

const userSchemas = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('common.index'),
    type: 'index'
  },
  {
    field: 'team',
    label: '班组'
  },
  {
    field: 'userid',
    label: '工号'
  },
  {
    field: 'username',
    label: '姓名'
  },
  {
    field: 'action',
    label: t('common.action'),
    slots: {
      default: (scope: any) => {
        return (
          <ElButton link size="small" onClick={() => selected.value.users.splice(scope.$index, 1)}>
            删除
          </ElButton>
        )
      }
    }
  }
])
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<TaskType | null>(null)
const actionType = ref('')

const AddAction = async () => {
  dialogTitle.value = t('common.add')
  const elTableExpose = await getElTableExpose()
  const select = elTableExpose?.getSelectionRows().map((v: TaskType) => v)
  if (!select || select.length === 0) {
    ElMessage.warning('请先选择派工工单')
    return
  }
  selected.value.team = select && select.length > 0 ? (select[0].team as string) : null
  selected.value.tickets = select?.map((v: TaskType) => v.ticket_id) || []
  dialogVisible.value = true
  actionType.value = 'add'
}

const delLoading = ref(false)

const delData = async (row: TaskType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TaskType) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: TaskType, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'common.edit' : 'common.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData && selected.value.users.length > 0) {
    saveLoading.value = true
    const pyload: any[] = []
    for (const item of selected.value.users) {
      for (const ticket of selected.value.tickets) {
        pyload.push({
          ticket_id: ticket,
          ...item
        })
      }
    }
    try {
      const res = await addAssignApi(pyload)
      if (res) {
        dialogVisible.value = false
        getList()
      }
    } finally {
      saveLoading.value = false
    }
  }
}

const selected = ref<{ team: any; tickets: string[]; users: any[] }>({
  team: null,
  tickets: [],
  users: []
})

// 选择用户
const selectUserDialog = ref(false)
const selectUserRef = ref<ComponentRef<typeof Write>>()

const onSelectUser = async () => {
  const write = unref(selectUserRef)
  const formData = await write?.submit()
  if (formData) {
    try {
      const datas = formData.map((item) => {
        return {
          userid: item.userid,
          username: item.username,
          team: item.team
        }
      })
      selected.value.users = selected.value.users.concat(datas)
    } finally {
      selectUserDialog.value = false
    }
  }
}

// watch(
//   () => selected.value.users,
//   (val) => {
//     if (!val) return []
//     setValues(val)
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )
useEventBus({
  name: 'updateTask',
  callback: async () => {
    getList()
  }
})
</script>

<template>
  <ContentWrap>
    <Search
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
      :show-expand="true"
      expand-field="team"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction">{{ t('common.add') }}</ElButton>
      <!-- <ElButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('common.del') }}
      </ElButton> -->
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      :fit="true"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="900px" max-height="380px">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :selected-tickets="selected.tickets"
      :selected-team="selected.team"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('common.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('common.close') }}</ElButton>
    </template>

    <Table :columns="userSchemas" node-key="id" :data="selected.users" />
  </Dialog>

  <Dialog v-model="selectUserDialog" title="选择派工人员" width="800px" max-height="600px">
    <UserTable ref="selectUserRef" :team="selected.team" />
    <template #footer>
      <ElButton type="primary" @click="onSelectUser"> 确定 </ElButton>
      <ElButton @click="selectUserDialog = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
</template>
